<template>
  <div class="">
    <h1>搜索页面</h1>
    <input type="text" v-model="search" />
    <button @click="gotolist">搜索</button>

    <hr />
    <h5>搜索历史记录</h5>
    <button @click="clear">清空</button>
    <p v-for="(item, index) in history" :key="index">{{ item }}</p>
  </div>
</template>

<script>
import { Dialog } from "vant";
export default {
  data() {
    return {
      search: "",
      history: JSON.parse(localStorage.getItem("his")) || [],
    };
  },
  mounted() {},
  methods: {
    gotolist() {
      if (this.history.length >= 3) {
        this.history.pop();
        this.history.unshift(this.search);
        localStorage.setItem("his", JSON.stringify(this.history));
      } else {
        this.history.unshift(this.search);
        localStorage.setItem("his", JSON.stringify(this.history));
      }

      this.$router.push({
        path: "/list",
        query: {
          search: this.search,
        },
      });
    },
    clear() {
      Dialog.confirm({
        title: "标题",
        message: "是否清空",
      })
        .then(() => {
          // on confirm
          this.history = [];
          localStorage.removeItem("his");
        })
        .catch(() => {
          // on cancel
        });
    },
  },
  components: {},
};
</script>

<style lang="scss"></style>
